package com.tzy.nowcoder.leetcode;

import com.tzy.nowcoder.leetcode.entity.Department;
import java.util.ArrayList;
import java.util.List;

/**
 * 招聘季节一般都在金三银四，或者金九银十。最近在这五六月份，陆陆续续面试了十几个高级前端。有一套考察算法的小题目。后台返回一个扁平的数据结构，转成树。
 * 我们看下题目：打平的数据内容如下：
 * let arr = [
 *     {"id": 1, name: "部门1", "parentId": 0},
 *     {"id": 2, name: "部门2", "parentId": 1},
 *     {"id": 3, name: "部门3", "parentId": 1},
 *     {"id": 4, name: "部门4", "parentId": 3},
 *     {"id": 5, name: "部门5", "parentId": 4},
 * ]
 *
 * 输出结果
 * [
 *     {
 *         ""id"": 1,
 *         "name": "部门1",
 *         ""parentId"": 0,
 *         "children": [
 *             {
 *                 ""id"": 2,
 *                 "name": "部门2",
 *                 ""parentId"": 1,
 *                 "children": []
 *             },
 *             {
 *                 ""id"": 3,
 *                 "name": "部门3",
 *                 ""parentId"": 1,
 *                 "children": [
 *                     // 结果 ,,,
 *                 ]
 *             }
 *         ]
 *     }
 * ]
 *
 * 我们的要求很简单，可以先不用考虑性能问题。实现功能即可

 * 链接：https://juejin.cn/post/6983904373508145189
 */
public class ArrayToTree {

    public static void main(String[] args) {
        ArrayList<Department> list = new ArrayList<>();
        list.add(new Department(1,"dept1",0));
        list.add(new Department(2,"dept2",1));
        list.add(new Department(3,"dept3",2));
        list.add(new Department(4,"dept4",3));
        System.out.println( arrayToTree(list,1) );

    }
    /**
     * 转换方法
     */
    static ArrayList arrayToTree (ArrayList<Department> data,Integer parentId){
         ArrayList result = new ArrayList();
        getChildren(data, result, parentId);
        return result;
    }

    /**
     *
     * @param data
     * @param result
     * @param parentId
     * @return
     */
    private static void getChildren(ArrayList<Department> data, List<Department> result, Integer parentId) {
        for (Department d:data){
            if(d.getParentId()==parentId){
                ArrayList<Department> newResult = new ArrayList<>();
                newResult.add(d);
                getChildren(data, d.getChildren(), parentId);

            }
        }
    }
    void test(){
        ArrayList<Department> list = new ArrayList<>();
        list.add(new Department(1,"dept1",0));
        list.add(new Department(2,"dept2",1));
        list.add(new Department(3,"dept3",2));
        list.add(new Department(4,"dept4",3));

    //        System.out.println(list);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getParentId()!=0){
                ArrayList<Department> departments = new ArrayList<>();
                departments.add(list.get(i));
                list.get(0).setChildren( departments );
            }


        }
        System.out.println(list);
    }

}
